// 导入axios
import axios from 'axios';
// import { MessageBox, Message } from "element-ui";
// import router from '../router/index';
import router from '@/router';

// 通过axios.create方法创建一个axios实例，用request接收
const request = axios.create({
  // 指定请求的根路径
  // baseURL: 'http://tf.mdp.caiyunapi.com',
  // baseURL: 'http://182.151.56.222:10002/api',
  baseURL: 'https://fp.shifang.caiyunapi.com/api',
  timeout: 10000 // request timeout
});
// console.log(localStorage.getItem('tk'))
// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // do something before request is sent
    // if (store.getters.token) {
    //     // 请求自动添加header的token
    config.headers['Authorization'] =
      localStorage.getItem('tk_type') + ' ' + localStorage.getItem('tk');
    // }
    // config.headers['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMzU0MDc4MzQ3NyIsImV4cCI6MTY4MTg3MTU2NH0._94cu1bXcqBiPUsXtWax0wLt1tKd6HI-un9uCFkrvhE'
    return config;
  },
  (error) => {
    // do something with request error
    // console.log(error); // for debug

    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    // console.log(response)
    const res = response.data;
    // 请求成功都是200
    if (response.status !== 200) {
      // Message({
      //     message: res.message || "Error",
      //     type: "error",
      //     duration: 5 * 1000,
      // });
      return Promise.reject(new Error(res.message || 'Error'));
    } else {
      return res;
    }
  },
  (error) => {
    if (error.response.status === 401) {
      // 401登陆超时
      MessageBox.confirm('登陆超时,请重新登陆', '您已登出', {
        confirmButtonText: '重新登陆',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // store.dispatch("user/resetToken").then(() => {
        //     location.reload();
        // });
        localStorage.clear();
        router.push('/');
      });
      return Promise.resolve('登陆异常已处理');
    }
    // 406错误
    if (error.response.status === 406) {
      Message({
        message: error.response.data.detail,
        type: 'error',
        duration: 5 * 1000
      });
      return Promise.reject('异常已处理');
    }

    return Promise.reject(error);
  }
);

export default request;
